package cn.com.header.zbpk.helper;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Objects;
import java.util.UnknownFormatConversionException;

/**
 * 汉字转换成拼音
 *
 * @author luohaidian
 * @date 2017-09-14
 * @time 10:27
 */
public class SpellHelper {

    public static String getPinYin(String str) {
        if (Objects.nonNull(str)) {
            char[] arr = str.toCharArray();
            // 设置汉字拼音输出格式
            HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            format.setVCharType(HanyuPinyinVCharType.WITH_V);
            StringBuilder result = new StringBuilder();
            String cacheItem;
            try {
                for (char c : arr) {
                    cacheItem = Character.toString(c);
                    //判断是否为汉字字符
                    if (cacheItem.matches("[\\u4E00-\\u9FA5]+")) {
                        // 第一个为汉语拼音
                        cacheItem = PinyinHelper.toHanyuPinyinStringArray(c, format)[0];
                    }
                    result.append(cacheItem);
                }
                return result.toString();
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                throw new UnknownFormatConversionException("汉字转拼音出错!!!");
            }
        }
        return null;
    }

}
